package com.ideal.manage.esms.service.project;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ideal.manage.esms.bean.DTO.PageDto;
import com.ideal.manage.esms.bean.project.EquipmentManage;
import com.ideal.manage.esms.bean.project.EquipmentTemperatureConf;
import com.ideal.manage.esms.bean.project.ParameterInfo;
import com.ideal.manage.esms.bean.sys.User;
import com.ideal.manage.esms.config.shiro.MyShiroRealm;
import com.ideal.manage.esms.repository.framework.MySpecification;
import com.ideal.manage.esms.repository.framework.SpecificationOperator;
import com.ideal.manage.esms.repository.programme.ParameterInfoRepository;
import com.ideal.manage.esms.repository.project.EquipmentManageRepository;
import com.ideal.manage.esms.repository.project.EquipmentTemperatureConfRepository;
import com.ideal.manage.esms.repository.system.UserRepository;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created By Dai On 2018/4/27
 * Remark: 工程配置 - 对象管理 - 模组温度配置 Service
 */
@Service
public class EquipmentTemperatureConfService {
    @Autowired
    private EquipmentManageRepository equipmentManageRepository;
    @Autowired
    private EquipmentTemperatureConfRepository equipmentTemperatureConfRepository;
    @Autowired
    private ParameterInfoRepository parameterInfoRepository;
    @Autowired
    private UserRepository userRepository;

    /**
     * 工程配置 -> 对象管理 -> 模组温度配置 -> 数据表
     *
     * @param pageNum
     * @param request
     * @return
     */
    public PageDto findAll(int pageNum, HttpServletRequest request) {
        // 1. 获取所有的电池组
        Sort sort = new Sort(Sort.Direction.DESC, "updateTime");
        List<SpecificationOperator> operators = new ArrayList<SpecificationOperator>() {{
            add(new SpecificationOperator("isValid", "1", "EQ"));       //存在
            add(new SpecificationOperator("equipmentType", "3", "EQ")); //电池组
        }};
        MySpecification<EquipmentManage> mySpecifications = new MySpecification<>(operators);
        Pageable pageable = new PageRequest(pageNum, 10, sort);
        Page<EquipmentManage> page = equipmentManageRepository.findAll(mySpecifications, pageable);
        // 设置PageDto
        List<EquipmentManage> parameters = page.getContent();
        // 2.找到当前页所有的电池组下的电池单体
        List<EquipmentManage> oneList = new ArrayList<EquipmentManage>();
        for (EquipmentManage equipmentManage : parameters) {
            oneList.addAll(equipmentManageRepository.findByParentId(equipmentManage.getId()));
        }
        // 3. 找到所有的温度配置
        List<EquipmentTemperatureConf> equipmentTemperatureConfList = equipmentTemperatureConfRepository.findByEquipmentList(oneList);
        equipmentTemperatureConfList.sort((EquipmentTemperatureConf e1, EquipmentTemperatureConf e2) -> e1.getId().compareTo(e2.getId()));
        // 4. 把所有的温度配置塞到电池组下面
        for (EquipmentManage equipmentManage : parameters) {    //遍历所有的电池组
            List<JSONObject> batteryAndTemp = new ArrayList<>();
            for (EquipmentTemperatureConf one : equipmentTemperatureConfList) {
                String id = one.getEquipment().getParent().getId();
                if (id.equals(equipmentManage.getId())) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("battery_id", one.getEquipment().getId());
                    jsonObject.put("battery_name", one.getEquipment().getName());
                    jsonObject.put("tmp_id", one.getParameterInfo().getId());
                    jsonObject.put("tmp_name", one.getParameterInfo().getName());
                    batteryAndTemp.add(jsonObject);
                }
            }
            equipmentManage.setBatteryAndTemp(batteryAndTemp);
        }
        long total = page.getTotalElements();
        PageDto pageDto = new PageDto();
        pageDto.setRows(parameters);
        pageDto.setTotal(total);
        return pageDto;
    }

    /**
     * 根据电池单体列表找到所有的温度配置
     *
     * @param equipmentManageList
     * @return
     */
    public List<EquipmentTemperatureConf> findByEquipmentList(List<EquipmentManage> equipmentManageList) {
        return equipmentTemperatureConfRepository.findByEquipmentList(equipmentManageList);
    }

    /**
     * 工程配置 -> 对象管理 -> 模组温度配置 -> 配置 -> 保存
     *
     * @param data
     * @return
     */
    public String temperatureSave(String id, String data) {
        JSONArray jsonArray = JSONArray.parseArray(data);
        // 1. 找到当电池组下的电池单体
        List<EquipmentManage> oneList = equipmentManageRepository.findByParentId(id);
        // 2. 找到所有的配置, 把所有的都删除掉
        List<EquipmentTemperatureConf> list = new ArrayList<EquipmentTemperatureConf>(){{
            addAll(equipmentTemperatureConfRepository.findByEquipmentList(oneList));
        }};
        list.forEach(equipmentTemperatureConf -> equipmentTemperatureConf.setIsValid(0));
        Date date = new Date();
        // 获取当前登录用户
        MyShiroRealm.ShiroUser shiroUser = (MyShiroRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        User user = userRepository.findOne(shiroUser.getId());
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String battery_id = jsonObject.getString("battery");
            String tem_id = jsonObject.getString("tem");
            boolean shouldCreate = true;    // 用于检测是否已经有了这个battery对应的模组温度配置
            for (EquipmentTemperatureConf equipmentTemperatureConf : list) {
                if (equipmentTemperatureConf.getEquipment().getId().equals(battery_id)) {
                    if (!equipmentTemperatureConf.getParameterInfo().getId().equals(tem_id)) {
                        // 如果模组温度不对的话重新设置一下模组温度并保存
                        equipmentTemperatureConf.setParameterInfo(parameterInfoRepository.findOne(tem_id));
                        equipmentTemperatureConf.setUpdateTime(date);
                        equipmentTemperatureConf.setIsValid(1);
                        shouldCreate = false;   // 表示list中已经有了个battery对应的配置
                        break;
                    }
                }
            }
            if (shouldCreate) { // 如果没有对应的配置的话添加进去一个新的配置
                EquipmentManage equipmentManage = equipmentManageRepository.findOne(battery_id);
                ParameterInfo parameterInfo = parameterInfoRepository.findOne(tem_id);
                EquipmentTemperatureConf equipmentTemperatureConf = new EquipmentTemperatureConf();
                equipmentTemperatureConf.setCreateTime(date);
                equipmentTemperatureConf.setUpdateTime(date);
                equipmentTemperatureConf.setEquipment(equipmentManage);
                equipmentTemperatureConf.setParameterInfo(parameterInfo);
                equipmentTemperatureConf.setCreateUser(user);
                list.add(equipmentTemperatureConf);
            }
        }
        equipmentTemperatureConfRepository.save(list);
        return "保存成功";
    }
}
